//通讯模块

import cEnumMgr from "../Enum/cEnumMgr"
import cEnumMds from "../Enum/cEnumMds"
import cEnumMsg from "../Enum/cEnumMsg"
import aconsole from "../librarys/ts/api_console"
import wbsocket from "../librarys/ts/api_websocket"
import CWebScoket from "../SuperMgr/cWebSocket"
import CScriptMgr from "../SuperMgr/cSpriteMgr";
import cModuleMgr from "../SuperMgr/cModuleMgr"
import cDataMgr from "../DataMgr/cDataMgr"
export default class cMessageModule extends CWebScoket {
    private ws:wbsocket = new wbsocket(this);
    constructor(){
        //注册模块
        super(cEnumMds.mssegModule);
        //连接地址
        this.host = "ws://192.168.1.6:23001";
        //启动连接
        this.ws.connect()
    }

    //连接成功
    public onopen():void{
        //启动心跳
        this.heartbeat()
        //断线重连
        let login:s2c_loginResult = cDataMgr.getData(cEnumMsg.s2c_loginResult)
        if(login){
            let mod:cModuleMgr = cModuleMgr.getModule(cEnumMds.loginModule)
            mod.changeStart()
        }else{
            let mod:cModuleMgr = cModuleMgr.getModule(cEnumMds.loginModule)
            mod.changeStart()
        }
    }

    //网络心跳
    public heartbeat():void{
        if(this.ws.readyState()){
            setTimeout(()=>{
                this.sendcmds(["heartbeat"])
                this.heartbeat()
            },60*900)
        }
    }

    //断开网络
    public onclose():void{
        setTimeout(()=>{
            this.ws.connect()  
        },500)
    }

    //接受消息
    public onmessage(data:msgBody):void{
        let cmd  = data.cmds.pop();
        let mod:typeof CScriptMgr=null;
        switch(cmd){
            case cEnumMgr.login:{mod=this.getModule(cEnumMds.loginModule)}break//登陆
            case cEnumMgr.lobby:{mod=this.getModule(cEnumMds.lobbyModule)}break//大厅
            //case cEnumMgr.table:{mod=this.getModule(cEnumMds.tableModule)}break//桌子
            //case cEnumMgr.games:{mod=this.getModule(cEnumMds.gamesModule);};break;//游戏
        }

        //派发消息
        if(mod instanceof CScriptMgr){
            mod.dispatchs(data);
        }
        else{
            aconsole.msgLog(cmd + ":No recipient was found")
        }
    }

    //发送消息
    public sendmail(name:string,cmds:string[],data:any){
        this.ws.sendmail(name,cmds,data);
    }

    //发送消息
    public sendcmds(cmds:string[]){
        this.sendmail("msgBody",cmds,{});
     }

}